package com.huixuebao.after.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huixuebao.after.dto.DataDTO;
import com.huixuebao.after.dto.LoginDTO;
import com.huixuebao.after.dto.SmsCodeDTO;
import com.huixuebao.after.entity.CaptchaEntity;
import com.huixuebao.after.entity.UserEntity;
import com.huixuebao.after.mapper.CaptchaMapper;
import com.huixuebao.after.mapper.TokenMapper;
import com.huixuebao.after.mapper.UserMapper;
import com.huixuebao.after.service.CaptchaService;
import com.huixuebao.after.service.LoginService;
import com.huixuebao.after.util.CaptchaUtil;
import com.huixuebao.after.util.LoginUtil;
import com.huixuebao.after.util.SendSms;
import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.common.enumeration.ResultCodeEnum;
import com.huixuebao.common.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    TokenMapper tokenMapper;
    @Autowired
    CaptchaService captchaService;
    @Autowired
    CaptchaMapper captchaMapper;

    /**
     * 登陆系统
     * @param loginDTO
     * @return
     */
    @Override
    public ApiResult login(LoginDTO loginDTO) {
        ApiResult apiResult = new ApiResult();
        try{
            //登陆类型
            String loginType = loginDTO.getLoginType();
            //手机号码
            String userCode = loginDTO.getUserCode();
            //手机验证码
            String captchaValue = loginDTO.getCaptchaValue();
            //密码
            String passWord = loginDTO.getPassWord();
            if (LoginUtil.LOGIN_METHOD_PASSWORD.equals(loginType)){
                if (StrUtil.isNotEmpty(userCode) && StrUtil.isNotEmpty(passWord)){
                    UserEntity code = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUserCode,userCode));
                    if (code != null){
                        if ((code.getUserState() == null || code.getUserState() != 0) && !code.isDelete()){
                            if (code.getPassword().equals(SecureUtil.md5(passWord))){
                                DataDTO dataDTO = new DataDTO();
                                Map<String,String> map = new HashMap<>();
                                map.put("userId",code.getId());
                                dataDTO.setData(JWTUtils.getToken(map));
                                apiResult.setData(dataDTO);
                                apiResult.setSuccess(true);
                                apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                                apiResult.setMessage("账号和密码登陆成功!!");
                            }else {
                                apiResult.setSuccess(false);
                                apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                                apiResult.setMessage("请输入正确的密码!!");
                            }
                        }else {
                            apiResult.setSuccess(false);
                            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                            apiResult.setMessage("该账号已被停用!!");
                        }
                    }else {
                        apiResult.setSuccess(false);
                        apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                        apiResult.setMessage("账号和密码不正确!!");
                    }
                }else {
                    apiResult.setSuccess(false);
                    apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                    apiResult.setMessage("登陆账号或密码不能为空!!");
                }
            }else {
                UserEntity code = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUserCode, userCode));
                String mobileNo = code.getMobileNo();
                if (captchaService.checkCaptcha(null, CaptchaUtil.CAPTCHA_TYPE_MOBILE, captchaValue, mobileNo)) {
                    if (StrUtil.isNotEmpty(code.getUserCode()) && StrUtil.isNotEmpty(mobileNo)) {
                        if ((code.getUserState() == null || code.getUserState() != 0) && !code.isDelete()) {
                            DataDTO dataDTO = new DataDTO();
                            Map<String, String> hashMap = new HashMap<>();
                            hashMap.put("userId", code.getId());
                            String accessToken = JWTUtils.getToken(hashMap);
                            dataDTO.setData(accessToken);
                            apiResult.setData(dataDTO);
                            apiResult.setSuccess(true);
                            apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                            apiResult.setMessage("手机验证码登陆成功!!");
                            captchaMapper.delete(new LambdaQueryWrapper<CaptchaEntity>().eq(CaptchaEntity::getPhone,mobileNo));
                        } else {
                            apiResult.setSuccess(false);
                            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                            apiResult.setMessage("账号已被停用");
                        }
                    } else {
                        apiResult.setSuccess(false);
                        apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                        apiResult.setMessage("手机号未注册用户!!");
                    }
                }else {
                    apiResult.setSuccess(false);
                    apiResult.setMessage("请输入正确到验证码信息!!");
                }
            }
        }catch (Exception e){
            log.info("login:" + e.getMessage());
            apiResult.setSuccess(false);
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("登陆异常!!" + e.getMessage());
        }
        return apiResult;
    }

    @Override
    public ApiResult getSmsCode(SmsCodeDTO smsCodeDTO) {
        ApiResult apiResult = new ApiResult();
        try {
            String code = smsCodeDTO.getUserCode();
            UserEntity userCode = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUserCode, code));
            String phone = userCode.getMobileNo();
            if (userCode != null) {
                String smsCode = CaptchaUtil.generateCode();
                SendSms.sendCaptchaCode(phone, smsCode);
                CaptchaEntity captcha = new CaptchaEntity();
                captcha.setCaptchaType(CaptchaUtil.CAPTCHA_TYPE_MOBILE);
                captcha.setCaptchaValue(smsCode);
                captcha.setCreateTime(new Date());
                captcha.setPhone(phone);
                captchaMapper.insert(captcha);
                apiResult.setSuccess(true);
                apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                apiResult.setMessage("汇学保后台管理系统发送验证码成功!!");
            } else {
                log.info("当前手机号为注册后台管理系统，请联系管理员!!");
                apiResult.setSuccess(false);
                apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                apiResult.setMessage("请联系管理员，手机号没有注册后台系统!!");
            }
        } catch (Exception e) {
            log.info("发送验证码失败!!");
            apiResult.setSuccess(false);
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("发送短信验证码失败!!");
        }
        return apiResult;
    }
}
